/*
 * Copyright (C) 2009 Show SMS open source project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bydavy.android.showsms;

//~--- non-JDK imports --------------------------------------------------------

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import android.hardware.SensorListener;
import android.hardware.SensorManager;

import android.os.Bundle;

import android.preference.PreferenceManager;

import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bydavy.util.showsms.Log;

//~--- JDK imports ------------------------------------------------------------

import java.util.Timer;
import java.util.TimerTask;

/**
 * Class description
 *
 *
 * @version 1.0, 09/07/27
 * @author Davy L.
 */
public class ShakeCalibrationActivity extends Activity {
    //~--- fields -------------------------------------------------------------

    /** Field description */
    private TimerTask MyTimerTask = null;

    // ~--- fields -------------------------------------------------------------

    /** Field description */
    private float maxShake = 0;

    /** Field description */
    private Timer timer = new Timer();

    /** Field description */
    private SensorListener sensorListenerDetect = new SensorListener() {
        @Override
        public void onAccuracyChanged(int sensor, int accuracy) {

            // TODO Auto-generated method stub
        }
        @Override
        public void onSensorChanged(int sensor, float[] values) {
            switch (sensor) {
            case SensorManager.SENSOR_ACCELEROMETER :
                boolean shaked = false;

                if (Math.abs(values[0]) > maxShake) {
                    shaked = true;
                }

                if (shaked) {
                    Context context = getApplicationContext();

                    Toast.makeText(context, "Shaked", Toast.LENGTH_SHORT).show();
                    shaked = false;
                }

                break;
            }
        }
    };

    /** Field description */
    private SensorListener sensorListenerCalibrate = new SensorListener() {
        @Override
        public void onAccuracyChanged(int sensor, int accuracy) {

            // TODO Auto-generated method stub
        }
        @Override
        public void onSensorChanged(int sensor, float[] values) {
            switch (sensor) {
            case SensorManager.SENSOR_ACCELEROMETER :
                float value = values[0];
                float absValue;

                absValue = Math.abs(value);

                if (absValue > maxShake) {
                    maxShake = absValue;
                    maxCheckTV.setText(String.valueOf(maxShake));
                }

                break;
            }
        }
    };

    /** Field description */
    private Button BCalibrate;

    /** Field description */
    private Button BDetect;

    /** Field description */
    private Builder dialogCalibration;

    /** Field description */
    private Builder dialogTest;

    /** Field description */
    private SensorManager mSensorManager;

    /** Field description */
    private TextView maxCheckTV;

    //~--- methods ------------------------------------------------------------

    // ~--- methods ------------------------------------------------------------

    /**
     * Method description
     *
     *
     * @param savedInstanceState
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v("ShakeCalibrationActivity : onCreate()");
        setContentView(R.layout.shake_calibration);
        loadPreferences();
        setupDialog();
        maxCheckTV     = (TextView) findViewById(R.id.TVMaxChecked);
        BCalibrate     = (Button) findViewById(R.id.BCalibrate);
        BDetect        = (Button) findViewById(R.id.BDetect);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mSensorManager.unregisterListener(sensorListenerCalibrate);
        BCalibrate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialogCalibration.show();
                maxShake = 0;
                mSensorManager.registerListener(sensorListenerCalibrate,
                                                SensorManager.SENSOR_ACCELEROMETER
                                                | SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_UI);
            }
        });
        BDetect.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialogTest.show();
                mSensorManager.registerListener(sensorListenerDetect,
                                                SensorManager.SENSOR_ACCELEROMETER
                                                | SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_UI);
            }
        });
    }

    /**
     * Method description
     *
     */
    public void onStop() {
        super.onStop();
        Log.v("ShakeCalibrationActivity : onStop()");
        mSensorManager.unregisterListener(sensorListenerCalibrate);
        mSensorManager.unregisterListener(sensorListenerDetect);
    }

    /**
     * Method description
     *
     */
    private void loadPreferences() {
        Log.v("ShakeCalibrationActivity : loadPreferences()");

        SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        // loading display time from SharedPreferences
        String shake_sensitivity_def = getString(R.preferences.shake_sensitivity_def);

        maxShake = Float.valueOf(mySharedPreferences.getString(getString(R.preferences.shake_sensitivity_key),
                shake_sensitivity_def));
    }

    /**
     * Method description
     *
     */
    private void savePreferences() {
        Log.v("ShakeCalibrationActivity : savePreferences()");

        SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        Editor            editor              = mySharedPreferences.edit();

        editor.putFloat(getString(R.preferences.shake_sensitivity_key), maxShake);
        editor.commit();
    }

    /**
     * Method description
     *
     */
    private void setupDialog() {
        dialogCalibration = new AlertDialog.Builder(this).setTitle("Calibration").setMessage(
            "Shake your phone and click OK to finish").setNeutralButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                mSensorManager.unregisterListener(sensorListenerCalibrate);
                savePreferences();
            }
        });
        dialogTest = new AlertDialog.Builder(this).setTitle("Test").setMessage(
            "Shake your phone and a message will be display when a shake is detected").setNeutralButton(
            "Quit", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                mSensorManager.unregisterListener(sensorListenerDetect);
            }
        });
    }
}
